<?php
defined('IN_YZMPHP') or exit('Access Denied');
class xlswriter{
	public $excel;
	public $my_format=[];
	public $number_keys=[];
	public $center_keys=[];
	public $filename;
	public $keys;
	public $column = 1;
	
	//初始化，读取配置
    public function __construct($type,$model='',$sheet_name='Sheet1'){
        $config = ['path' => YZMPHP_PATH.'uploads/xlswriter' . '/'];
		$excel = new \Vtiful\Kernel\Excel($config);
		//获取文件名
		$this->filename = $this->get_excel_filename($type);
		//自由内存模式，可能占内存过高
		if(!$model){
			$this->excel  = $excel->fileName($this->filename.'.xlsx', $sheet_name);
		}else{
			//固定内存模式 WPS 需要关闭 zip64
			$this->excel  = $excel->constMemory($this->filename.'.xlsx',$sheet_name,false);
		}
		//读锁
		if(getcache('LOCK::download_lock')){
			//exit('有导出任务在执行，请稍后执行！');
		}
		//懒人锁
		setcache('LOCK::download_lock',1,200);
		//自定义单元格格式初始化
		$this->format();
		//标题数据
		$this->insert_header($type);
    }
	
	public function format(){
		$handle = $this->excel->getHandle();
        $format1    = new \Vtiful\Kernel\Format($handle);
        $format2    = new \Vtiful\Kernel\Format($handle);
		$format3    = new \Vtiful\Kernel\Format($handle);
		
        //标题格式
        $this->my_format['title_style'] = $format1->fontSize(10)//字体
            ->bold()//加粗
			->border(\Vtiful\Kernel\Format::BORDER_THIN)//边框
			->background(0x8CC7FD)//背景颜色
            ->align(\Vtiful\Kernel\Format::FORMAT_ALIGN_CENTER, \Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_CENTER)//水平垂直居中
            ->toResource();

        //默认格式水平居中
        $this->my_format['global_style_center'] = $format2->fontSize(10)//字体
			->border(\Vtiful\Kernel\Format::BORDER_THIN)//边框
			->align(\Vtiful\Kernel\Format::FORMAT_ALIGN_CENTER, \Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_CENTER)//垂直居中
			->toResource();
			
		//默认格式
		$this->my_format['global_style'] = $format3->fontSize(10)//字体
			->border(\Vtiful\Kernel\Format::BORDER_THIN)//边框
			->align(\Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_CENTER)//垂直居中
			->toResource();
	}
	
	public function add_sheet($type,$sheet_name,$data){
		$this->excel->addSheet($sheet_name);
		$this->insert_header($type);
		$this->column = 1;
		$this->insert_data($data);
	}
	
	public function insert_header($type){
		$header = get_excel_field($type);
		$this->keys = array_keys($header);
        $header_len = count($header);
		//最后一列列标
        $end = strtoupper(chr(65 + $header_len - 1));
		//首行添加筛选
		$this->excel->autoFilter("A1:{$end}1");
        //冻结首行
        $this->excel->freezePanes(1, 0);

		//标题行高
		$this->excel->setRow("A1",25);
		$this->number_keys = [];
		$this->center_keys = [];
		$header_key = 0;
		foreach($header as $k=>$v){
			$this->excel->insertText(0, $header_key, $v['name'], NULL, $this->my_format['title_style']);
			//当前列
			$this_key = strtoupper(chr(65 + $header_key));
			//列宽
			$this->excel->setColumn("{$this_key}:{$this_key}", $v['width']);
			//数字格式化字段键值列表
			if(isset($v['format'])){
				if($v['format'] == 'number') {
					$this->number_keys[] = $header_key;
				}
			}
			if(isset($v['align'])){
				if($v['align'] == 'center') {
					$this->center_keys[] = $header_key;
				}
			}
			$header_key++;
		}
		//return $this->output();exit;
	}

	public function insert_data($data){
		$array = [];
		$date_arr = ['modified','created','send_date','pay_date','order_date','sales_add_time','confirm_date'];
		//echo '循环前：'.memory_get_usage();
		foreach($data as $val){
			$datas = [];
			foreach($this->keys as $v){
				if(in_array($v,$date_arr)){
					if($val[$v]){
						$datas[] = date('Y-m-d H:i:s',$val[$v]);
					}else{
						$datas[] = '-';
					}
				}else{
					$datas[] = $val[$v];
				}
			}
			$array[] = $datas;
		}
		unset($datas);
		$number_keys = $this->number_keys;
		$center_keys = $this->center_keys;
		$header_key = 0;
		foreach($array as $k=>$v){
			foreach($v as $key=>$val){
				if(in_array($key,$center_keys)){
					$this_style = $this->my_format['global_style_center'];
				}else{
					$this_style = $this->my_format['global_style'];
				}
				//格式格式化避免显示错误
				if(in_array($key,$number_keys)){
					$this->excel->insertText($this->column, $key, intval($val), '0', $this_style);
					continue;
				}
				$this->excel->insertText($this->column, $key, $val, NULL, $this_style);
			}
			//行高
			$this->excel->setRow("A".($this->column+1),20);
			$this->column++;
		}
		unset($array);
		unset($data);
	}
	
	public function output($page=''){
        // 数据
        $filePath = $this->excel->output();
		$filename = $this->filename;
		delcache('LOCK::download_lock');
		//echo SITE_URL.'uploads/xlswriter/'.$filename.'.xlsx';exit;
		return  SITE_URL.'uploads/xlswriter/'.$filename.'.xlsx';
		/*excel文件流形式输出
        header("Content-Disposition:attachment;filename={$filename}.xlsx");
		ob_clean();
		flush();

        $re = copy($filePath, 'php://output');
        if ($re === false) {
            $err = 'failed to write output';
        } else {
            $err = '';
        }
        @unlink($filePath);
		*/
	}
	
	
	//获取缓存目录
	private function get_tmp_dir(){
		$tmp = ini_get('upload_tmp_dir');
		if ($tmp !== False && file_exists($tmp)) {
			return realpath($tmp);
		}
		return realpath(sys_get_temp_dir());
	}
	
	//获取文件名
	private function get_excel_filename($type){
		$download_time = date('Y_m_d_H_i_s');
		switch($type){
			case 'orders':
				$filename = '订单_';
				break;
			case 'sku':
				$filename = '商品_';
				break;
			case 'inventorys':
				$filename = '库存_';
				break;
			case 'ts_buhuo':
				$filename = '唐狮补货_';
				break;
			case 'ys_dingzuo':
				$filename= '佑晟订做_';
				break;
			case 'wp_buhuo':
				$filename= '唯品补货_';
				break;
			case 'purchaser':
				$filename = '订做采购单_';
				break;
			default:
				$filename = '其他_';
		}
		return $filename.$download_time;
	}

	
}

